package com.kuang.service.Impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kuang.entity.*;
import com.kuang.mapper.SysUserMapper;
import com.kuang.security.TokenManager;
import com.kuang.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private TokenManager tokenManager;

    /**
     * 根据用户名获取用户信息
     */
    @Override
    public User selectByUsername(String username) {
        SysUser sysUser = userMapper.selectByUsername(username);
        User user = new User();
        if (Objects.nonNull(sysUser)) {
            BeanUtils.copyProperties(sysUser, user);
        }
        return user;
    }

    /**
     * 根据用户名获取用户对象
     */
    @Override
    public SysUser selectBySysUser(String username) {
        SysUser sysUser = userMapper.selectByUsername(username);
        return sysUser;
    }

    /**
     * 根据id 修改用户对象
     */
    @Override
    public void updateByPrimaryKeySelective(SysUser sysUser) {
        userMapper.updateByPrimaryKeySelective(sysUser);
    }


    /**
     * 根据 id 修改用户密码
     */
    @Override
    public String updatePasswordByID(SysUser sysUser) {
        // 加密密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        // 1. 根据用户id查询当前用户对象(加密密码)
        SysUser row = userMapper.selectByPrimaryKey(sysUser.getId());
        // 3. 拿两个密码进行判断
        boolean matches = encoder.matches(sysUser.getPassword(), row.getPassword());

        if(matches){
            // 密码加密
            String encode = encoder.encode(sysUser.getNewPassword());
            sysUser.setPassword(encode);
            int ref = userMapper.updatePasswordByID(sysUser);
            String  str = "密码相同修改成功";
            return str; // 返回成功状态
        } else {
            String str = "原密码错误";
            return str;

        }
    }



    /**
     * 忘记密码
     */
    @Override
    public String PasswordByID(SysUser sysUser) {
        // 加密密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        // 密码加密
        String encode = encoder.encode(sysUser.getPassword());
        sysUser.setPassword(encode);
        int ref = userMapper.updatePasswordByID(sysUser);
        if (ref == 1){
            String str = "密码修改成功";
            return str;
        }
        return "错误";

    }


    /**
     * 注册
     */
    @Override
    public void addSysUser(SysUser sysUser) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(sysUser.getPassword());
        sysUser.setPassword(encode);
        userMapper.insertSelective(sysUser);
    }

    /**
     * 新增教师用户
     */
    @Override
    public Integer saveTeacher(Teacher teacher) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        // 1. 将 Teacher 对象转为JSON格式的字符串
        String jsonStr = objectMapper.writeValueAsString(teacher);
        // 2. 将 JSON格式 转换为SysUser对象
        SysUser user = objectMapper.readValue(jsonStr, SysUser.class);
//        user.setSpeciality("无");
        user.setCredit("无");
        // 3. 删除重复的工号信息
        userMapper.deleteByUsername(user.getUsername());
        // 3. 新增数据库
        int sum = userMapper.insert(user);
        return sum;
    }

    /**
     * 新增学生用户
     */
    @Override
    public Integer saveStudent(Student student) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        // 1. 将 Student 对象转为JSON格式的字符串
        String jsonStr = objectMapper.writeValueAsString(student);
        // 2. 将 JSON格式 转换为SysUser对象
        SysUser user = objectMapper.readValue(jsonStr, SysUser.class);
        // 3. 删除重复的学号信息
        userMapper.deleteByUsername(user.getUsername());
        // 4. 新增数据库
        int sum = userMapper.insertSelective(user);
        return sum;
    }

    /**
     * 获取用户的菜单信息
     */
    @Override
    public List<SysPermission> getMenuList(String token) {
        // 1. 从token中获取用户名
        String username = tokenManager.getUsernameFromToken(token);
        // 2. 根据用户名获取用户权限
        SysUser sysUser = userMapper.selectByUsername(username);
        // 3. 根据用户权限查询所有的菜单信息
        List<SysPermission> menuList = userMapper.getMenuList(sysUser.getUse_role());
        return menuList;
    }

    @Override
    public List<SysUser> selectUserAll() {
        return userMapper.selectUserAll();
    }

    /**
     * 查询所有用户信息
     */

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }


    /**
     *教师系统：学生分页查询
     * **/
    public PageInfo TeFindBySearchStudent(Params params) {
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<SysUser> list = userMapper.TeFindBySearchStudent(params);
        return PageInfo.of(list);
    }
    /**
     * 管理员：学生分页查询
     **/
    @Override
    public PageInfo findBySearchStudent(Params params) {
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<SysUser> list = userMapper.findBySearchStudent(params);
        return PageInfo.of(list);
    }
    /**
     * 管理员：教师分页查询
     **/
    @Override
    public PageInfo findBySearchTeacher(Params params) {
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<SysUser> list = userMapper.findBySearchTeacher(params);
        return PageInfo.of(list);
    }

    /*
     * 定义查询学院、专业和用户的方法
     * */
    @Override
    public List<Department> getAllDepartments() {
        return userMapper.getAllDepartments();
    }

    @Override
    public List<Major> getMajorsByDepartmentId(Long departmentId) {
        return userMapper.getMajorsByDepartmentId(departmentId);
    }

    @Override
    public List<SysUser> getSysUsersByMajorId(Long majorId) {
        return userMapper.getSysUsersByMajorId(majorId);
    }
    /***
     * 注册账号申请管理
     * **/
    @Override
    public int accountManagement(SysUser sysUser) {
        int i=userMapper.accountManagement(sysUser);
        return i;

    }


}
